package HomeWork.hw3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 8:51
 **/
@WebServlet("/jpg")
public class jpg extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.获取请求参数（filename），得知要展示的图片名
        2.根据图片名，获得图片存放的真实路径realpath
        3.通过输入流读取图片
        4.通过输出流将图片展示在页面上

        * */
        String filename=req.getParameter("filename");
        System.out.println(filename);
        //获取图片真实路径
        //通过servletcontext对象
        ServletContext servletContext =req.getServletContext();
        String realPath=servletContext.getRealPath("/img/"+filename);
        System.out.println(realPath);
        //通过字节输入流读取文件，相应的字节输出流写数据到页面
        FileInputStream fis=new FileInputStream(realPath);
        ServletOutputStream outputStream =resp.getOutputStream();

        byte[] bytes=new byte[1024*2];
        int len=0;
        while((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        fis.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
